import pandas as pd
import datetime
from pyecharts import options as opts
from pyecharts.charts import Bar, Line
import datas_fetch

# 获取设备近一月运行数据
def operating_data(equipMentNumber):
    date = (datetime.datetime.strptime(datas_fetch.TimeInfos['datetime'].max(), '%Y-%m-%d') + datetime.timedelta(
        days=-30)).strftime('%Y-%m-%d')
    einfo = datas_fetch.TimeInfos[
        (datas_fetch.TimeInfos['equipmentnumber'] == equipMentNumber) & (datas_fetch.TimeInfos['datetime'] > date)]
    return einfo

# 设备运行状态
def equipment_state(equipMentNumber):
    einfo = operating_data(equipMentNumber)
    bar = Bar(init_opts=opts.InitOpts(width="100%", height='380px'))

    bar.add_xaxis([equipMentNumber])
    bar.add_yaxis("运行时长", [round(einfo['worktime'].mean(), 2)], color='#9999ff')
    bar.add_yaxis("待机时长", [round(einfo['standbytime'].mean(), 2)], color='#33ffff')
    bar.add_yaxis("停机时长", [round(einfo['stoptime'].mean(), 2)], color='#33ff99')
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title='设备状态', subtitle='近30天平均值', title_textstyle_opts={"color": "white"}),
        legend_opts=opts.LegendOpts(
            is_show=True, pos_right='0', pos_top='0', item_width=10,
            textstyle_opts=opts.TextStyleOpts(color='white', font_size=10)),
        xaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))),
        yaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white")))
    )
    return bar


# 设备开机率
def equipment_startrate(equipMentNumber):
    einfo = operating_data(equipMentNumber)
    line = Line(init_opts=opts.InitOpts(width='100%', height='380px'))
    line.add_xaxis([i[-5:] for i in einfo['datetime'].tolist()])
    line.add_yaxis("", einfo['startrate'].tolist(), color='#33ffff')
    line.set_global_opts(
        title_opts=opts.TitleOpts(title="设备开机率(%)", title_textstyle_opts={"color": "white"}),
        datazoom_opts=opts.DataZoomOpts(range_start=0, range_end=60),
        xaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))),
        yaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white")))
    )
    return line

def equipments_infos(equipMentNumber):
    # 根据设备编号获取设备名字
    name = datas_fetch.InstallInfos[datas_fetch.InstallInfos['equipmentnumber'] == equipMentNumber]['name'].tolist()[0]
    # 根据设备名字获取所有同名设备
    equipments = datas_fetch.InstallInfos[datas_fetch.InstallInfos.name == name]
    # 获取timeinfos中最新日期往前倒推30天的日期序列
    date = (datetime.datetime.strptime(datas_fetch.TimeInfos['datetime'].max(), '%Y-%m-%d') + datetime.timedelta(
        days=-30)).strftime('%Y-%m-%d')
    tinfos = datas_fetch.TimeInfos[datas_fetch.TimeInfos.datetime > date]
    # 获取该日期序列中所有同名设备的运行统计数据
    einfos = pd.merge(equipments, tinfos, on='equipmentnumber', how='inner')
    einfos.drop(columns=['companyid', 'name', 'datetime'], inplace=True)
    einfos = round(einfos.groupby('equipmentnumber', as_index=False).mean(), 2)
    einfos['srank'] = einfos['startrate'].rank(method='dense', ascending=False)
    # einfos['erank'] = einfos['efficiency'].rank(method='dense',ascending = False)
    einfos.fillna(0, inplace=True)
    einfos['score'] = einfos['srank']  # + einfos['erank']
    return einfos

def equipments_statetop(equipMentNumber):
    name = datas_fetch.InstallInfos[datas_fetch.InstallInfos['equipmentnumber'] == equipMentNumber].name.tolist()[0]
    einfos = equipments_infos(equipMentNumber)
    etop = einfos.sort_values(by='score')[0:5]
    c = Bar(init_opts=opts.InitOpts(width="100%", height='770px'))
    c.add_xaxis(etop['equipmentnumber'].tolist())
    c.add_yaxis('运行时长', etop['worktime'].tolist(), color='#9999ff', stack="stack1")
    c.add_yaxis('待机时长', etop['standbytime'].tolist(), color='#33ffff', stack="stack1")
    c.add_yaxis('停机时长', etop['stoptime'].tolist(), color='#33ff99', stack="stack1")
    c.set_global_opts(title_opts=opts.TitleOpts(name + '设备状态TOP5', title_textstyle_opts={"color": "white"}),
        legend_opts=opts.LegendOpts(
            is_show=True, pos_right='5', pos_top='0', item_width=10,
            textstyle_opts=opts.TextStyleOpts(color='white', font_size=10),
        ),
        xaxis_opts=opts.AxisOpts(
            split_number=24, min_=0, max_=24,
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        ),
        yaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        )
    )
    c.reversal_axis()
    c.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    return c
